// store/countdown.js
import { ref, computed } from 'vue'

// 倒计时基础状态
const totalSeconds = ref(40 * 60 ) // 默认40分钟9秒
const remainingSeconds = ref(totalSeconds.value)
const isCounting = ref(false)
let timerId = null

// 记录是否需要重置倒计时
const shouldReset = ref(false)

// 指定需要重置倒计时的页面路径列表
const resetPages = ref([
  'pages/case/case',    // 首页
  
  // 其他需要重置倒计时的页面路径
])

// 格式化时间
const formattedTime = computed(() => {
  const hours = Math.floor(remainingSeconds.value / 3600)
  const minutes = Math.floor((remainingSeconds.value % 3600) / 60)
  const seconds = remainingSeconds.value % 60
  return [hours, minutes, seconds].map(v => v.toString().padStart(2, '0')).join(':')
})

// 启动倒计时
const startCountdown = (currentPagePath) => {
  // 如果从指定页面返回，重置倒计时
  if (shouldReset.value) {
    resetCountdown()
    shouldReset.value = false
  }
  
  if (!isCounting.value) {
    isCounting.value = true
    timerId = setInterval(() => {
      if (remainingSeconds.value > 0) {
        remainingSeconds.value--
      } else {
        clearInterval(timerId)
        isCounting.value = false
      }
    }, 1000)
  }
  
  // 记录当前页面路径
  lastActivePage.value = currentPagePath
}

// 停止倒计时
const stopCountdown = () => {
  clearInterval(timerId)
  isCounting.value = false
}

// 重置倒计时
const resetCountdown = () => {
  stopCountdown()
  remainingSeconds.value = totalSeconds.value
}

// 记录上一个活跃页面
const lastActivePage = ref('')

// 检查是否需要设置重置标志
const checkResetFlag = (toPagePath) => {
  // 如果即将进入的页面在重置列表中，设置重置标志
  if (resetPages.value.includes(toPagePath)) {
    shouldReset.value = true
  }
}

// 获取当前页面路径
const getCurrentPagePath = () => {
  const pages = getCurrentPages()
  if (pages.length) {
    return pages[pages.length - 1].route
  }
  return ''
}

export {
  remainingSeconds,
  formattedTime,
  isCounting,
  startCountdown,
  stopCountdown,
  resetCountdown,
  getCurrentPagePath,
  checkResetFlag
}